package ee.parameterConverter.impl;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import ee.metadataUtils.ClassUtils;
import ee.metadataUtils.PropertyMetadata;
import ee.metadataUtils.impl.AdapterNotFoundException;
import ee.parameterConverter.Converter;
import ee.parameterConverter.ParameterPropertyMetadata;
import ee.parameterConverter.Validator;

public class ParameterPropertyMetadataImpl implements ParameterPropertyMetadata {

	private String _optionalAnnotationName;
	private boolean _isOptionalSet;
	private boolean _optional;

	private PropertyMetadata _propertyMetadata;
	
	public ParameterPropertyMetadataImpl(PropertyMetadata propertyMetadata, String optionalAnnotationName)
	{
		_propertyMetadata = propertyMetadata;
		_optionalAnnotationName = optionalAnnotationName;
	}

	@Override
	public boolean isOptional() {
		
		if (!_isOptionalSet)
		{
			for (Annotation annotation : _propertyMetadata.getAnnotations())
			{
				if (annotation.annotationType().getSimpleName().equals(_optionalAnnotationName))
				{
					_optional = true;
					break;
				}
			}
			_isOptionalSet = true;
		}
		
		return _optional;
	}

	@Override
	public Object getDefaultValue(Object context) {
		return ClassUtils.getDefaultValue(getType());
	}
	
	@Override
	public Validator getValidator() {
		return null;
	}
	
	@Override
	public Converter<String[], ?> getConverter() {
		return null;
	}
	
	@Override
	public String getName() {
		return _propertyMetadata.getName();
	}
	
	@Override
	public Type getGenericType() {
		return _propertyMetadata.getGenericType();
	}

	@Override
	public void setValue(Object instance, Object value) throws Throwable {
		_propertyMetadata.setValue(instance, value);
	}

	@Override
	public Class<?> getType() {
		return _propertyMetadata.getType();
	}

	@Override
	public Object getValue(Object instance) throws Throwable {
		return _propertyMetadata.getValue(instance);
	}

	@Override
	public Annotation[] getAnnotations() {
		return _propertyMetadata.getAnnotations();
	}

	@Override
	public <T> T getAdapter(Class<T> adapterType) throws AdapterNotFoundException {
		return _propertyMetadata.getAdapter(adapterType);
	}

}
